import asyncio
import random

from sqlalchemy.future import select

from database import init_db, close_db, AsyncSessionLocal
from models import User, Order


# 生成随机用户名
def generate_username():
    return f"user_{random.randint(1000, 9999)}"


# 生成随机邮箱
def generate_email(username):
    domains = ["gmail.com", "hotmail.com", "yahoo.com", "outlook.com", "qq.com"]
    return f"{username}@{random.choice(domains)}"


# 生成随机全名
def generate_full_name():
    first_names = ["张", "王", "李", "赵", "刘", "陈", "杨", "黄", "周", "吴"]
    last_names = ["伟", "芳", "娜", "秀英", "敏", "静", "强", "磊", "军", "洋"]
    return f"{random.choice(first_names)}{random.choice(last_names)}"


# 生成随机产品
def generate_products():
    products = ['苹果手机', '4090显卡', '鼠标', '耳机', '卫生纸', '碗', '冰箱']
    return f'{random.choice(products)}'


# 随机生成订单
def generate_orders():
    orders = []
    for _ in range(random.randint(1, 10)):
        order = Order(
            product=generate_products(),
            amount=(random.randint(1, 10000) / 100),
        )
        orders.append(order)
    return orders


# 初始化数据库并插入测试数据
async def init_test_data(num_users=100):
    # 初始化数据库（创建表）
    await init_db()

    # 创建会话
    async with AsyncSessionLocal() as session:
        # 检查是否已有数据
        result = await session.execute(select(User).limit(1))
        if result.scalars().first() is not None:
            print("数据库中已有数据，跳过初始化")
            return

        # 批量创建用户
        users = []
        for i in range(num_users):
            username = generate_username()

            user = User(
                username=username,
                email=generate_email(username),
                full_name=generate_full_name(),
                orders=generate_orders()
            )
            users.append(user)

        # 添加到会话并提交
        session.add_all(users)
        await session.commit()

        print(f"成功创建 {num_users} 个测试用户")


# 主函数
async def main():
    try:
        await init_test_data()
    finally:
        await close_db()


# 运行初始化脚本
if __name__ == "__main__":
    asyncio.run(main())
